package com.example.android.services

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import androidx.core.content.edit
import com.example.android.R
import com.example.android.extensions.StringBody
import com.example.android.utils.Api
import com.example.android.utils.JsonUtil
import com.example.android.utils.models.Form
import com.example.android.utils.models.MyResult
import com.google.gson.Gson
import java.util.*
import kotlin.collections.HashMap

/**
 * @ClassName LogInService
 * @Author Ryan Kamanri
 * @Date 2022/6/1
 * @Description
 **/
class LogInService(
    private val _Api: Api,
    private val _JsonUtil: JsonUtil,
    private val _HashMapStorage: HashMap<String, String>,
    private val _SharedService: SharedService
) {
    suspend fun LogIn(userName: String, userPassword: String): MyResult<Form> {

        val form = Form(
            "userName" to Base64.getEncoder().encodeToString(userName.encodeToByteArray()),
            "userPassword" to Base64.getEncoder().encodeToString(userPassword.encodeToByteArray())
        )

        val response = _Api.Post("/user/login", _JsonUtil.ToJson(form))

        // add cookies if needed
        val cookieList = arrayListOf<String>()

        response.headers.forEach {
            Log.d(toString(), "${it.first}: ${it.second}")
            if (it.first == "Set-Cookie") {
                cookieList.add(it.second)
            }
        }

        _SharedService.SetLocalCookies(cookieList)


        _Api.SetPreset {
            cookieList.forEach { cookie ->
                it.addHeader("cookie", cookie)
            }
        }

        val resForm = _JsonUtil.FromJsonObject(response.StringBody())
        when (resForm["code"]) {
            MyResult.LOG_IN_SUCCESS -> {
                val token = resForm.Get("data").Get<String>("token")
                _HashMapStorage["token"] = token
                return resForm.AsMyResult()
            }
        }
        return resForm.AsMyResult()

    }

}
